package cn.wolfcode.trip.app.controller;

import cn.wolfcode.trip.base.query.RegionQueryObject;
import cn.wolfcode.trip.base.query.StrategyQuery;
import cn.wolfcode.trip.base.service.IRegionService;
import cn.wolfcode.trip.base.service.IStrategyService;
import com.github.pagehelper.PageInfo;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.HashMap;

@RestController
@RequestMapping("regions")
public class RegionController {
    @Autowired
    private IRegionService regionService;
    @Autowired
    private IStrategyService strategyService;
    @Autowired
    private ServletContext ctx;
    //回显整个地区
    @GetMapping
    public Object  getRegions(){
        return regionService.list();
    }
    //回显推荐的地区
    @GetMapping("/{state}")
    public Object  getCommendRegions(RegionQueryObject qo){

        return regionService.getCommendRegions(qo);
    }

    //全部攻略的分页查询,,        分页查询,接受头是json类型
    @GetMapping(value = "/{regionId}/strategies",produces = "application/json;charset=utf-8")
    public Object getStrategiesJson(StrategyQuery qo) throws Exception {
        //全部攻略
        return strategyService.query(qo);
    }

    //查询地区下面的所有攻略,和具有推荐状态的攻略
    @GetMapping(value = "/{regionId}/strategies",produces = "text/html;charset=utf-8")
    public void getStrategiesHtml(@PathVariable Long regionId, HttpServletResponse resp) throws Exception {
        //返回结果
        HashMap<String, Object> map = new HashMap<String, Object>();
        //查询出所有的状态,并且分页
        StrategyQuery qo = new StrategyQuery();
        qo.setRegionId(regionId);
        qo.setPageSize(8);
        PageInfo listAll = strategyService.query(qo);
        map.put("listAll",listAll);
       //查询出来所有推荐的攻略,
        qo.setState(1L);
        qo.setPageSize(0);
        PageInfo listCommend = strategyService.query(qo);
        map.put("listCommend",listCommend);
        //freemarket模板
        Configuration cfg = new Configuration(Configuration.VERSION_2_3_20);
        cfg.setDirectoryForTemplateLoading(new File(ctx.getRealPath("/template")));
        Template temp = cfg.getTemplate("strategy.ftl","utf-8");
        //输出到浏览器.. map为根目录,不会模板中显示
        temp.process(map,resp.getWriter());
    }

}
